package com.zhixin.zhixinmall.controller;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhixin.zhixinmall.constant.JwtConstant;
import com.zhixin.zhixinmall.entity.pojo.Wxuserinfo;
import com.zhixin.zhixinmall.entity.result.ResultMap;
import com.zhixin.zhixinmall.properties.WechatProperties;
import com.zhixin.zhixinmall.service.WxuserinfoService;
import com.zhixin.zhixinmall.util.HttpClientUtil;
import com.zhixin.zhixinmall.util.JwtUtil;

/**
 * @author cyc
 * @date 2023/10/08 16:08:19
 */
@CrossOrigin
@RestController
@RequestMapping("/wechat")
public class WechatController {
    private Logger logger = LoggerFactory.getLogger(WechatController.class);

    @Autowired
    WechatProperties wechatProperties;

    @Autowired
    HttpClientUtil httpClientUtil;

    @Autowired
    WxuserinfoService wxuserinfoService;

    /**
     * 微信用户登录
     *
     * @return
     */
    @PostMapping("/wxlogin")
    public ResultMap wxLogin(@RequestBody Wxuserinfo wxUserInfo) {
        logger.info("wxlogin:{}", JSON.toJSONString(wxUserInfo));
        String jscode2sessionUrl = wechatProperties.getJscode2sessionUrl() + "?appid=" + wechatProperties.getAppid()
                + "&secret=" + wechatProperties.getSecret() + "&js_code=" + wxUserInfo.getCode()
                + "&grant_type=authorization_code";
        System.out.println(jscode2sessionUrl);
        String result = httpClientUtil.sendHttpGet(jscode2sessionUrl);
        logger.info("jscode2session:{}", result);
        JSONObject jsonObject = JSON.parseObject(result);
        String openid = jsonObject.get("openid").toString();
        logger.info("openid:{}", openid);
        // 插入用户到数据库 假如说 用户不存在 我们插入用户 如果用户存在 我们更新用户
        Wxuserinfo resultWxUserInfo = wxuserinfoService.getOne(new QueryWrapper<Wxuserinfo>().eq("openid", openid));
        if (resultWxUserInfo == null) {
            logger.info("用户不存在，插入用户");
            wxUserInfo.setOpenid(openid);
            wxuserinfoService.save(wxUserInfo);
        } else {
            logger.info("用户已存在，更新用户");
            resultWxUserInfo.setNickName(wxUserInfo.getNickName());
            resultWxUserInfo.setAvatarUrl(wxUserInfo.getAvatarUrl());
            wxuserinfoService.updateById(resultWxUserInfo);
        }
        // 利用jwt生成token返回到前端
        String token = JwtUtil.createJwt(openid, wxUserInfo.getNickName(), JwtConstant.JWT_TTL);
        Map<String, Object> resultMap = new ConcurrentHashMap<>(4);
        resultMap.put("token", token);
        return ResultMap.ok(resultMap);
    }

}
